<template>
  <el-dialog
    v-model="dialogVisible"
    title="角色分配"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="role-assignment">
      <div class="user-info">
        <h4>{{ userInfo?.userName || "未知用户" }}</h4>
        <p>用户ID: {{ userInfo?.userId || "N/A" }}</p>
      </div>

      <el-divider />

      <div v-loading="loading" class="role-selection">
        <h5>可分配角色</h5>
        <div class="role-list">
          <el-checkbox-group v-model="selectedRoleIds">
            <div
              v-for="role in availableRoles"
              :key="role.id"
              class="role-item"
            >
              <el-checkbox
                :value="role.id"
                :disabled="isSystemRole(role.roleKey) && !canManageSystemRole"
              >
                <div class="role-content">
                  <div class="role-header">
                    <span class="role-name">{{ role.roleName }}</span>
                    <el-tag :type="getRoleStatusType(role.status)" size="small">
                      {{ formatRoleStatus(role.status) }}
                    </el-tag>
                  </div>
                  <div class="role-description">
                    {{ role.description || "暂无描述" }}
                  </div>
                  <div class="role-key">角色标识: {{ role.roleKey }}</div>
                </div>
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </div>

        <div v-if="selectedRoleIds.length > 0" class="role-summary">
          <h6>已选择角色 ({{ selectedRoleIds.length }})</h6>
          <div class="selected-roles">
            <el-tag
              v-for="roleId in selectedRoleIds"
              :key="roleId"
              type="primary"
              size="small"
              closable
              @close="removeRole(roleId)"
            >
              {{ getRoleName(roleId) }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="saving"
          :disabled="!hasChanges"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  getAvailableRolesApi,
  getUserRolesApi,
  assignRolesToUserApi,
  RoleManagementUtils,
  type RoleInfo
} from "@/api/role-management";
import { type UserInfo } from "@/api/user-management";

interface Props {
  visible: boolean;
  userInfo: UserInfo | null;
}

interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const dialogVisible = ref(false);
const loading = ref(false);
const saving = ref(false);
const availableRoles = ref<RoleInfo[]>([]);
const selectedRoleIds = ref<number[]>([]);
const originalRoleIds = ref<number[]>([]);

// 计算属性
const canManageSystemRole = computed(() => {
  // 这里可以根据当前用户权限判断是否可以管理系统角色
  // 暂时返回true，实际应该根据用户权限判断
  return true;
});

const hasChanges = computed(() => {
  return !RoleManagementUtils.compareRoleArrays(
    selectedRoleIds.value,
    originalRoleIds.value
  );
});

// 监听visible变化
watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
    if (val && props.userInfo) {
      loadData();
    }
  },
  { immediate: true }
);

// 监听dialogVisible变化
watch(dialogVisible, val => {
  emit("update:visible", val);
});

/**
 * 加载数据
 */
const loadData = async () => {
  if (!props.userInfo?.userId) {
    ElMessage.error("用户信息无效");
    return;
  }

  loading.value = true;
  try {
    console.log("开始加载角色数据，用户ID:", props.userInfo.userId);

    // 并行加载可用角色和用户当前角色
    const [availableResult, userRolesResult] = await Promise.all([
      getAvailableRolesApi(),
      getUserRolesApi(props.userInfo.userId)
    ]);

    console.log("可用角色API响应:", availableResult);
    console.log("用户角色API响应:", userRolesResult);

    if (availableResult.code === 200) {
      availableRoles.value = availableResult.data || [];
      console.log("设置可用角色:", availableRoles.value);
    } else {
      ElMessage.error(availableResult.message || "获取可用角色失败");
      return;
    }

    if (userRolesResult.code === 200) {
      const userRoles = userRolesResult.data || [];
      const roleIds = RoleManagementUtils.extractRoleIds(userRoles);
      selectedRoleIds.value = [...roleIds];
      originalRoleIds.value = [...roleIds];
      console.log("设置用户角色:", roleIds);
    } else {
      ElMessage.error(userRolesResult.message || "获取用户角色失败");
    }
  } catch (error) {
    console.error("加载角色数据失败:", error);
    ElMessage.error("加载角色数据失败，请检查网络连接");
  } finally {
    loading.value = false;
  }
};

/**
 * 保存角色分配
 */
const handleSave = async () => {
  if (!props.userInfo?.userId) {
    ElMessage.error("用户信息无效");
    return;
  }

  // 验证角色ID有效性
  const validation = RoleManagementUtils.validateRoleIds(
    selectedRoleIds.value,
    availableRoles.value
  );
  if (!validation.valid) {
    ElMessage.error(`无效的角色ID: ${validation.invalidIds.join(", ")}`);
    return;
  }

  saving.value = true;
  try {
    const result = await assignRolesToUserApi(
      props.userInfo.userId,
      selectedRoleIds.value
    );

    if (result.code === 200) {
      ElMessage.success(result.message || "角色分配成功");
      originalRoleIds.value = [...selectedRoleIds.value];
      emit("success");
      handleClose();
    } else {
      ElMessage.error(result.message || "角色分配失败");
    }
  } catch (error) {
    console.error("角色分配失败:", error);
    ElMessage.error("角色分配失败");
  } finally {
    saving.value = false;
  }
};

/**
 * 关闭对话框
 */
const handleClose = () => {
  dialogVisible.value = false;
  // 重置数据
  selectedRoleIds.value = [...originalRoleIds.value];
};

/**
 * 移除角色
 */
const removeRole = (roleId: number) => {
  const index = selectedRoleIds.value.indexOf(roleId);
  if (index > -1) {
    selectedRoleIds.value.splice(index, 1);
  }
};

/**
 * 获取角色名称
 */
const getRoleName = (roleId: number): string => {
  const role = availableRoles.value.find(r => r.id === roleId);
  return role ? role.roleName : `角色${roleId}`;
};

/**
 * 检查是否为系统角色
 */
const isSystemRole = (roleKey: string): boolean => {
  return RoleManagementUtils.isSystemRole(roleKey);
};

/**
 * 格式化角色状态
 */
const formatRoleStatus = (status: string): string => {
  return RoleManagementUtils.formatRoleStatus(status);
};

/**
 * 获取角色状态类型
 */
const getRoleStatusType = (status: string): string => {
  return RoleManagementUtils.getRoleStatusType(status);
};
</script>

<style lang="scss" scoped>
.role-assignment {
  .user-info {
    text-align: center;

    h4 {
      margin: 0 0 8px;
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }

    p {
      margin: 0;
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
  }

  .role-selection {
    h5,
    h6 {
      margin: 0 0 16px;
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
    }

    h6 {
      margin-bottom: 12px;
      font-size: 14px;
    }
  }

  .role-list {
    max-height: 300px;
    overflow-y: auto;

    .role-item {
      padding: 12px;
      margin-bottom: 16px;
      border: 1px solid var(--el-border-color-light);
      border-radius: 8px;
      transition: all 0.3s;

      &:hover {
        background-color: var(--el-bg-color-page);
        border-color: var(--el-color-primary);
      }

      :deep(.el-checkbox) {
        width: 100%;

        .el-checkbox__label {
          width: 100%;
        }
      }
    }
  }

  .role-content {
    width: 100%;

    .role-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 8px;

      .role-name {
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }

    .role-description {
      margin-bottom: 4px;
      font-size: 14px;
      color: var(--el-text-color-regular);
    }

    .role-key {
      font-family: monospace;
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }

  .role-summary {
    padding: 16px;
    margin-top: 20px;
    background-color: var(--el-bg-color-page);
    border-radius: 8px;

    .selected-roles {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
